package org.sanguine.study.hometasks.second;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;

public class CountingRhymesOnArrayList {
	protected static final int STEP = 2;
	protected int numberOfGamers;
	protected List<Integer> list;
	protected ListIterator<Integer> iterator;

	public CountingRhymesOnArrayList(int N) {
		if (N <= 0) throw new IllegalArgumentException("N must be greater than zero");
		
		this.numberOfGamers = N;
	}

	public int getNumberOfPeople() {
		return (iterator == null) ? numberOfGamers : list.size();
	}
	
	public void startGame() {
		list = createList();
		for (int i=1; i <= numberOfGamers; i++) list.add(i);

		iterator = list.listIterator();
		moveAhead(STEP);
	}

	protected List<Integer> createList() {
		return new ArrayList<>(numberOfGamers);
	}

	private void moveAhead(int step) {
		for (int i = step; i > 0; i--) {
			if (!iterator.hasNext()) iterator = list.listIterator();
			iterator.next();
		}
	}

	public List<Integer> getPeople() {
		return Collections.unmodifiableList(list);
	}
	
	public int doTurn() {
		if (iterator == null) throw new IllegalStateException("Call startGame first");
		
		moveAhead(1);
		iterator.remove();
		moveAhead(STEP - 1);
		
		int people = getNumberOfPeople();
		if (people == 1) iterator = null;
		return people;
	}
}
